package vn.hanelsoft.newsduet.model.delegate;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import vn.hanelsoft.newsduet.common.UtilsCommon;
import vn.hanelsoft.newsduet.model.object.ObjectCategory;
import vn.hanelsoft.newsduet.model.object.ObjectNews;

public class ServiceDelegate {

	public static final String LINK_CATEGORY_INDIA = "http://newsduet.net/category/india/feed/";
	public static final String LINK_CATEGORY_WORLD = "http://newsduet.net/category/world/feed/";
	public static final String LINK_CATEGORY_BUSINESS = "http://newsduet.net/category/business/feed/";
	public static final String LINK_CATEGORY_TECHNOLOGY = "http://newsduet.net/category/technology/feed/";
	public static final String LINK_CATEGORY_HEALTH = "http://newsduet.net/category/health/feed/";
	public static final String LINK_CATEGORY_SCIENCE = "http://newsduet.net/category/science/feed/";
	public static final String LINK_CATEGORY_SPORT = "http://newsduet.net/category/sports/feed/";

	public static final String TAG_CHANNEL = "channel";
	public static final String TAG_TITLE = "title";
	public static final String TAG_LINK = "link";
	public static final String TAG_DESCRIPTION = "description";
	public static final String TAG_LAST_BUILD_DATE = "lastBuildDate";
	public static final String TAG_ITEM = "item";
	public static final String TAG_PUB_DATE = "pubDate";
	public static final String TAG_CATEGORY = "category";

	// Method read xml from server, return list object
	public static ObjectCategory readXML(String strUrl, boolean isHighlight) {
		ObjectCategory objectCategory = new ObjectCategory();
		ArrayList<ObjectNews> listNews = new ArrayList<ObjectNews>();

		//
		try {
			// URL url = new URL(strUrl);
			URL formattedUrl = new URL(strUrl);
			URLConnection connection = formattedUrl.openConnection();
			HttpURLConnection httpConnection = (HttpURLConnection) connection;
			httpConnection.setAllowUserInteraction(false);
			httpConnection.setInstanceFollowRedirects(true);
			httpConnection.setRequestMethod("GET");
			httpConnection.connect();
			InputStream in = null;
			if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
				in = httpConnection.getInputStream();

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(new InputSource(new InputStreamReader(in,
					"UTF-8")));
			doc.getDocumentElement().normalize();
			NodeList listChanel = doc.getElementsByTagName(TAG_CHANNEL);
			// Get size of the list
			int totalChanel = listChanel.getLength();
			for (int i = 0; i < totalChanel; i++) {
				Node currentNode = listChanel.item(i);
				NodeList nodeChild = currentNode.getChildNodes();
				int totalItem = nodeChild.getLength();
				for (int j = 0; j < totalItem; j++) {
					String nodeName = nodeChild.item(j).getNodeName();
					String nodeString = null;
					if (nodeChild.item(j).getFirstChild() != null) {
						nodeString = nodeChild.item(j).getFirstChild()
								.getNodeValue();
					}
					if (nodeString != null) {
						if (TAG_TITLE.equals(nodeName)) {
							objectCategory.setCategory_title(nodeString);
							// Log.d("Luong",
							// "____________________read xml category category_title: "
							// + nodeString);
						} else if (TAG_LINK.equals(nodeName)) {
							objectCategory.setCategory_link(nodeString);
							// Log.d("Luong",
							// "___________________________read xml category category_link: "
							// + nodeString);
						} else if (TAG_PUB_DATE.equals(nodeName)) {
							nodeString = nodeString.replace("+0000", "");
							objectCategory.setCategory_lastUpdate(nodeString
									.trim());
							// Log.d("Luong",
							// "____________________________________read xml category news_link: "
							// + nodeString);
						} else if (TAG_ITEM.equals(nodeName)) {
							
							if(isHighlight)
							{
								if(listNews.size() < 3)
								{
									Node currentNodeItem = nodeChild.item(j);
									NodeList nodeChildItem = currentNodeItem
											.getChildNodes();
									int totalChildItem = nodeChildItem.getLength();
									ObjectNews objectNews = new ObjectNews();
									objectNews.setNews_favourite("0");
									for (int k = 0; k < totalChildItem; k++) {
										String nodeItemName = nodeChildItem.item(k)
												.getNodeName();
										String nodeItemString = null;
										if (nodeChildItem.item(k).getFirstChild() != null) {
											nodeItemString = nodeChildItem.item(k)
													.getFirstChild().getNodeValue();
										}
										if (nodeItemString != null) {
											if (TAG_LINK.equals(nodeItemName)) {
												objectNews.setNews_link(nodeItemString);
//												Log.d("Luong",
//														"_______________==================news link: "
//																+ nodeItemString);
											} else if (TAG_DESCRIPTION
													.equals(nodeItemName)) {
												objectNews
														.setNews_description(nodeItemString);
												
												
												
												
//												Log.d("Luong",
//														"_______________==================news description: "
//																+ nodeItemString);
//												nodeItemString.replaceAll("\"", "\'");
												String src = UtilsCommon.subStringText(nodeItemString,"<img src=\"", "\" width=");
//												Log.d("Luong","_______________src: "+ src);
												 objectNews.setNews_imageSRC(src) ;
//												nodeItemString.replaceAll("\"", "\'");
//												Log.d("Luong",
//														"_______________==================news description: "
//																+ nodeItemString);
//												UtilsCommon.subStringText("> <img src='http://newsduet.net/wp-content/uploads/2014/05/uk-energy-too-cheap-says-study.jpg' width='460' height='276' alt='Electricity pylons' /> <p>", "<img", "/>");


											} else if (TAG_TITLE.equals(nodeItemName)) {
												objectNews
														.setNews_title(nodeItemString);
//												Log.d("Luong",
//														"_______________==================news title: "
//																+ nodeItemString);
											} else if (TAG_CATEGORY
													.equals(nodeItemName)) {
												objectNews
														.setNews_name_category(nodeItemString
																.trim());
//												Log.d("Luong",
//														"_______________==================news name category: "
//																+ nodeItemString);
											} else if (TAG_PUB_DATE
													.equals(nodeItemName)) {
												nodeItemString = nodeItemString
														.replace("+0000", "");
												objectNews
														.setNews_pubDate(nodeItemString
																.trim());
//												Log.d("Luong",
//														"_______________==================news pub date: "
//																+ nodeItemString);
											}

										}

									}
									listNews.add(objectNews);
								}
							}else{
								Node currentNodeItem = nodeChild.item(j);
								NodeList nodeChildItem = currentNodeItem
										.getChildNodes();
								int totalChildItem = nodeChildItem.getLength();
								ObjectNews objectNews = new ObjectNews();
								for (int k = 0; k < totalChildItem; k++) {
									String nodeItemName = nodeChildItem.item(k)
											.getNodeName();
									String nodeItemString = null;
									if (nodeChildItem.item(k).getFirstChild() != null) {
										nodeItemString = nodeChildItem.item(k)
												.getFirstChild().getNodeValue();
									}
									if (nodeItemString != null) {
										if (TAG_LINK.equals(nodeItemName)) {
											objectNews.setNews_link(nodeItemString);
//											Log.d("Luong",
//													"_______________==================news link: "
//															+ nodeItemString);
										} else if (TAG_DESCRIPTION
												.equals(nodeItemName)) {
											objectNews
													.setNews_description(nodeItemString);
											
											
											
											
//											Log.d("Luong",
//													"_______________==================news description: "
//															+ nodeItemString);
//											nodeItemString.replaceAll("\"", "\'");
											String src = UtilsCommon.subStringText(nodeItemString,"<img src=\"", "\" width=");
//											Log.d("Luong","_______________src: "+ src);
											 objectNews.setNews_imageSRC(src) ;
//											nodeItemString.replaceAll("\"", "\'");
//											Log.d("Luong",
//													"_______________==================news description: "
//															+ nodeItemString);
//											UtilsCommon.subStringText("> <img src='http://newsduet.net/wp-content/uploads/2014/05/uk-energy-too-cheap-says-study.jpg' width='460' height='276' alt='Electricity pylons' /> <p>", "<img", "/>");


										} else if (TAG_TITLE.equals(nodeItemName)) {
											objectNews
													.setNews_title(nodeItemString);
//											Log.d("Luong",
//													"_______________==================news title: "
//															+ nodeItemString);
										} else if (TAG_CATEGORY
												.equals(nodeItemName)) {
											objectNews
													.setNews_name_category(nodeItemString
															.trim());
//											Log.d("Luong",
//													"_______________==================news name category: "
//															+ nodeItemString);
										} else if (TAG_PUB_DATE
												.equals(nodeItemName)) {
											nodeItemString = nodeItemString
													.replace("+0000", "");
											objectNews
													.setNews_pubDate(nodeItemString
															.trim());
//											Log.d("Luong",
//													"_______________==================news pub date: "
//															+ nodeItemString);
										}

									}

								}
								listNews.add(objectNews);
							}
							
							
//							Log.d("Luong",
//									"________________________________________________________________________________");
						}
					}
				}
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		//

		objectCategory.setCategory_listNews(listNews);
		return objectCategory;
	}
}
